<?php

/*
 * 定义基础的配置信息
 */
namespace BI\Controller;

/**
 * Description of ConfigureController
 *
 * @author chenghui
 */
class ConfigureController {
    private $isCache;//是否使用缓存，1为使用，0为不使用
    private $config;//配置信息文件夹
    private $catch;//缓存信息文件夹
    private $sisCode;//分析代号
    private $dirName;//缓存路径
    
    /**
     * @初始化默认参数
     * @param type $sisCode
     * @param type $isCache
     */
    public function __construct($sisCode,$isCache){
        $this->config = 'Config';
        $this->catch = 'Catch';
        $this->sisCode = empty($sisCode)?'Bdata':$sisCode;
        $this->isCache = empty($isCache)?0:$isCache;
        $this->dirName = empty($sisCode)?'Bdata':$sisCode;
    }
    
    
    /**
     * @方法：获取基础配置表信息
     * @return type
     */
    public function initBaseConfig(){
        
        if($this->isCache>0){
         
            $file=$this->dirName.'/'.$this->config.'/'.'BaseConfig';
        
            $BaseConfig=F($file);
          
            if(empty($BaseConfig)){
                $BaseConfig['Base'] = $this->fetchBaseConfig();
                $BaseConfig['Axis'] = $this->fetchAxisConfig();
                $BaseConfig['Uom'] = $this->fetchUomConfig();
                $BaseConfig['Count'] = $this->fetchCountConfig();
               
                F($file,$BaseConfig);
            }
        }else{
            $BaseConfig['Base'] = $this->fetchBaseConfig();
            $BaseConfig['Axis'] = $this->fetchAxisConfig();
            $BaseConfig['Uom'] = $this->fetchUomConfig();
            $BaseConfig['Count'] = $this->fetchCountConfig();
        }        
        return $BaseConfig;
    }

    
    /**
     * @获取可作为分析维度的字段表达式
     * @param type $code
     * @return type
     */
    public function initAnalysisAxis(){
        if($this->isCache>0){
            $file=$this->dirName.'/'.$this->config.'/'.'AnalysisAxis';
            $AxisDetail=F($file);
            if(empty($AxisDetail)){
                $AxisDetail = $this->fetchAnalysisAxis();
                F($file,$AxisDetail);
            }
        }else{
            $AxisDetail = $this->fetchAnalysisAxis();
        }
        
        return $AxisDetail;
    }
    
    /**
     * @获取可作为统计维度的字段表达式
     * @param type $code
     * @return type
     */
    public function initCountAxis(){
        if($this->isCache>0){
            $file=$this->dirName.'/'.$this->config.'/'.'CountAxis';
            $CountAxisConfig=F($file);
            if(empty($CountAxisConfig)){
                $CountAxisConfig = $this->fetchCountAxis();
                F($file,$CountAxisConfig);
            }
        }else{
            $CountAxisConfig = $this->fetchCountAxis();
        }
        
        return $CountAxisConfig;
    }
    
    /**
     * @获取可作为条件的字段表达式
     * @param type $code
     * @return type
     */
    public function initCodition($defaultConditon){
        $array = empty($defaultConditon)?array():$defaultConditon;
        //获得条件项配置明细
        $allData=$this->fetchWhereAxis();
        
        //当存在默认值时，需要清除非选择项
        if(!empty($defaultConditon)){
            foreach($allData as $key=>$val){
                if(!in_array($key, $defaultConditon)){
                    unset($allData[$key]);
                }
            }
        }

        if($this->isCache>0){//需要缓存时
            foreach($allData as $key=>$var){
                $whereData[$key]=$this->fetchSingleWhere($key,$var);
                
                if($var['FieldType']==1){//对照时
                    $file=$this->dirName.'/'.$this->config.'/'.$key;
                    $where = F($file);
                    if(empty($where)){
                        $where = $this->fetchConditionDetail($var);
                        F($file,$where);
                    }
                    $whereData[$key]['item']=$where;
                }
            }
        }else{//不需要缓存
            $whereData=$this->fetchWhereData($data);
        }

        return $whereData;
    }
    
    
    /**
     * @获得特殊计算的表达式
     * @param type $code
     * @return type
     */
    public function initBdataSpecial(){
        if($this->isCache>0){
            $file=$this->dirName.'/'.$this->config.'/'.'BdataSpecial';
            $BdataSpecial=F($file);
            if(empty($BdataSpecial)){
                $BdataSpecial=$this->fetchBdataSpecial();
                F($file,$BdataSpecial);
            }
        }else{
            $BdataSpecial=$this->fetchBdataSpecial();
        }

        return $BdataSpecial;
    }
    
    /**
     * @获取菜单输出格式
     * @return string
     */
    public function initMenuFormat(){
        $menu = array(
                    'rank'=>'排名',
                    'yAxis'=>'统计',
                    'sums'=>'合计'
                    );
        return $menu;
    }

    /**
     * @根据参数配置识别数据库类型
     * @return type
     */
    public function getDBType(){
        $type = C('DB_TYPE');
        $type = strtoupper($type);
        
        if($type=='PDO'){
            $dns = C('DB_DSN');
            $array = explode(':', $dns);
            $dbType = strtoupper($array[0]);
        }
        return $dbType;
    }

    /**
     * @初始化图表格式
     * @return string
     */
    public function initChartFormat(){
        $chart = array(
                        'bar'=>'柱状图',
                        'sybar'=>'条形图',
                        'line'=>'折线图',
                        'pie'=>'饼状图',
                        'sline'=>'堆积折线图',
                        'xBar'=>'堆积柱状图',
                        'yBar'=>'堆积条形图',
                        'pxBar'=>'百分比堆积柱状图',
                        'pyBar'=>'百分比堆积条形图',
                        'fixed'=>'量价图'
                    );
        return $chart;
    }
    
    
    /**
     * @更新分析数据
     */
    public function getBdataImport_log(){
        //更新临时数据
        $this->updateTempDatabase();
        
        //配置信息的缓存路径
        $path = DATA_PATH.'/'.$this->dirName.'/'.$this->config.'/';
        $this->rmFiles($path);
        
        //缓存信息的缓存路径
        $path = DATA_PATH.'/'.$this->dirName.'/'.$this->catch.'/';
        $this->rmFiles($path);
    }

    /**
     * @读取基础数据库配置表
     * @return type
     */
    private function fetchBaseConfig(){
        $BdataBaseConfig = array();
        $sql='select Code,DataType,DataExp,Param,DigTable '
              . ' from '.C('DB_PREFIX').'BdataBase '
              ." where code='".$this->sisCode."'";
        $dataArr=  M()->query($sql);

        foreach($dataArr as $val){
            $BdataBaseConfig['Code']=$val['Code'];
            $BdataBaseConfig['DataType']=$val['DataType'];
            $BdataBaseConfig['DataExp']=$val['DataExp'];
            $BdataBaseConfig['Param']=$val['Param'];
            $BdataBaseConfig['DigTable']=$val['DigTable'];
        }
        return $BdataBaseConfig;
    }
    
     /**
     * @读取配置表数据
     * @return type
     */
    private function fetchAxisConfig(){
        $AxisConfig = array();
        $sql='select Upper(FieldColumn) as FieldColumn,FieldName,FieldType,Accuracy,DataColumn,Expression,Uom,ContrastSheet,ContrastId,ContrastName,ContrastSort,ContrastWhere,IsNull '
              . ' from '.C('DB_PREFIX').'Configure '
              . "where Code='".$this->sisCode."'";
        
        $dataArr=  M()->query($sql);
        
        foreach($dataArr as $val){
            $arr=array();
            $key=  $val['FieldColumn'];
            $arr['FieldName']=$val['FieldName'];
            $arr['FieldType']=$val['FieldType'];
            $arr['Accuracy']=$val['Accuracy'];
            $arr['DataColumn']=$val['DataColumn'];
            $arr['Expression']=$val['Expression'];
            $arr['Uom']=$val['Uom'];
            $arr['ContrastSheet']=$val['ContrastSheet'];
            $arr['ContrastId']=$val['ContrastId'];
            $arr['ContrastName']=$val['ContrastName'];
            $arr['ContrastSort']=$val['ContrastSort'];
            $arr['ContrastWhere']=$val['ContrastWhere'];
            $arr['IsNull']=$val['IsNull'];
            
            $AxisConfig[$key]=$arr;
        }
        
        //追加几个标准栏目的代号及名称
        $AxisConfig['rank']['FieldName']='排名';
        $AxisConfig['yAxis']['FieldName']='统计';
        $AxisConfig['sTotal']['FieldName']='小计';
        $AxisConfig['gTotal']['FieldName']='合计';
        
        return $AxisConfig;
    }
    
    
    /**
     * @读取单位配置信息
     * @return type
     */
    private function fetchUomConfig(){
        $UomConfig=array();
        $sql='select a.id as UomId,b.id as UomGroupId,a.title as UomName,IsMain,Rate '
             .' from '.C('DB_PREFIX')."uom".' as a '
             .' inner join '.C('DB_PREFIX')."uomgroup ".' as b on b.id=a.uomgroup ';
       
        $dataArr=M()->query($sql);
       // dump($dataArr);exit();
        foreach($dataArr as $val){
            $arr=array();
            $key=$val['UomId'];
            
            $arr['UomGroupId']=$val['UomGroupId'];
            $arr['UomName']=$val['UomName'];
            $arr['IsMain']=$val['IsMain'];
            $arr['Rate']=$val['Rate'];

            $UomConfig[$key]=$arr;
        }
        return $UomConfig;
    }
    
    
    /**
     * @获取统计规则信息
     * @return type
     */
    private function fetchCountConfig(){
        $CountConfig=array();
        $sql='select Id,Upper(Code) as Code,Title from '.C('DB_PREFIX').'count';
        $dataArr=M()->query($sql);

        foreach($dataArr as $val){
            $arr=array();
            $key=$val['Code'];
            $arr['Id']=$val['Id'];
            $arr['CountName']=$val['Title'];

            $CountConfig[$key]=$arr;
        }
        return $CountConfig;
    }
    
    
    /**
     * @解析维度配置明细
     * @return type
     */
    private function fetchAnalysisAxis(){
        $sql="select Upper(FieldColumn) as FieldColumn,FieldName,CountRules,UomGroup,Uom,DefaultValue as rules,FieldType,Sort,isAxis "
              . " from ".C('DB_PREFIX')."Configure "
              . " where Code='".$this->sisCode."'".' and isAxis > 0 '
              .' order by Sort';
        $dataArr=  M()->query($sql);
        return $dataArr;
    }
    
    
    /**
     * @解析统计维度配置明细
     * @return type
     */
    private function fetchCountAxis(){
        $sql='select Upper(FieldColumn) as FieldColumn,FieldName,CountRules,UomGroup,Uom,DefaultValue,FieldType,Sort '
              . " from ".C('DB_PREFIX')."Configure "
              . " where Code='".$this->sisCode."'".' and isCount > 0 '
              .' order by Sort';
        $dataArr=  M()->query($sql);
        return $dataArr;
    }
    
    
    /**
     * @获取配置表明细
     * @param type $var
     * @return type
     */
    private function fetchWhereAxis(){
        //需要缓存
        if($this->isCache > 0){
            $file=$this->dirName.'/'.$this->config.'/'.'AllCondition';
            $condition = F($file);
            if(empty($condition)){
                $condition = $this->fetchAllCondition();
                F($file,$condition);
            }
        }else{
            $condition = $this->fetchAllCondition();
        }        
        
        return $condition;
    }
    
    
    /**
     * @获得所有条件项明细
     * @return type
     */
    private function fetchAllCondition(){
        $result = array();
        $sql="select Upper(FieldColumn) as FieldColumn,FieldName,FieldType,b.title as UomName,button,ContrastSheet as cSheet,ContrastId as cId,ContrastName as cName,ContrastSort as cSort,ContrastWhere as cWhere "
                ." from ".C('DB_PREFIX')."Configure as a "
                ." left join ".C('DB_PREFIX')."uom as b on a.Uom=b.id "
                ." where code='".$this->sisCode."' and iswhere > 0 ".' order by sort';

        $data=M()->query($sql);
        
        foreach ($data as $val){
            $key = $val['FieldColumn'];
            $result[$key]['FieldName'] = $val['FieldName'];
            $result[$key]['FieldType'] = $val['FieldType'];
            $result[$key]['UomName'] = $val['UomName'];
            $result[$key]['button'] = $val['button'];
            $result[$key]['cSheet'] = $val['cSheet'];
            $result[$key]['cId'] = $val['cId'];
            $result[$key]['cName'] = $val['cName'];
            $result[$key]['cSort'] = $val['cSort'];
            $result[$key]['cWhere'] = $val['cWhere'];
        }
        return $result;
    }

    
     /**
     * @方法：根据配置表读取基础数据表明细
     * @param type $var
     * @return type
     */
    private function fetchConditionDetail($var){
        $where = empty($var['cWhere'])?'':' where '.$var['cWhere'];
        
        $sql='select '.$var['cId'].' as id,'.$var['cName'].' as title from '.$var['cSheet'].$where.' order by '.$var['cSort'];
        $Data=M()->query($sql);
        return $Data;
    }
    
    
    /**
     * 解析配置表数据:条件项
     * @param type $data
     * @return type
     */
    private function fetchWhereData($data){
        foreach($data as $key=>$var){
            $whredata[$key] = $this->fetchSingleWhere($key,$var);
            if($var['FieldType']==1){
                $whredata[$key]['item']=$this->fetchConditionDetail($var);
            }
        }
        return $whredata;
    }
    
    
    /**
     * @解析无对照关系的条件字段表达式
     * @param type $var
     */
    private function fetchSingleWhere($key,$var){
        $where['FieldColumn'] = $key;
        $where['FieldName'] = $var['FieldName'];
        $where['FieldType'] = $var['FieldType'];
        $where['UomName'] = $var['UomName'];
        $where['button'] = $var['button'];
        return $where;
    }

        /**
     * @读取特殊计算配置信息
     * @return type
     */
    private function fetchBdataSpecial(){
        $BdataSpecial = array();
        $sql="select Id,Upper(FieldCode) as FieldCode,Upper(FieldColumn) as FieldColumn,FieldExp,FieldValue,FieldOut,FieldRate "
              . " from ".C('DB_PREFIX')."BdataSpecial "
              . " where Code='".$this->sisCode."'";
        $dataArr=  M()->query($sql);

        foreach($dataArr as $val){
            $key=$val['Id'];
            $BS['FieldCode']=$val['FieldCode'];
            $BS['FieldColumn']=$val['FieldColumn'];
            $BS['FieldExp']=$val['FieldExp'];
            $BS['FieldValue']=$val['FieldValue'];
            $BS['FieldOut']=$val['FieldOut'];
            $BS['FieldRate']=$val['FieldRate'];
            $BdataSpecial[$key]=$BS;
        }
        return $BdataSpecial;
    }
    
    
    /**
     * @更新临时表数据：可将数据导入后，需要重建临时表的操作放于此方法
     */
    private function updateTempDatabase(){
        //更新供应数据
        M()->prepare('updateTempStockAnalyze');
        //更新项目坐标数据
        M()->prepare('updateTempProjectFormats');
    }
    
    
    /** 
     * @此方法为公共方法用来删除某个文件夹下的所有文件
     * @$path为缓存文件的路径
     * */
    private function rmFiles($path){        
        if($dh = opendir($path)){//打开Cache文件夹;        
            while(($file = readdir($dh))!==false){//遍历Cache目录,
                unlink($path.$file);//删除遍历到的每一个文件;
            }
            closedir($dh);
        }
    }

}
